package unclevenn.cloudmusic.until;

import io.minio.*;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;

@Component
public class MinioUntil {
    private String MinioEndPoint = null;
    private final static String Location = "us-east-1";

    private final MinioClient minioClient;

    private final static Integer DEFAULT_EXPIRY = 60;//min

    public MinioUntil(@Value("${minio.endpoint}") String minioEndPoint, @Value("${minio.access-key-id}") String minioAccessKeyId, @Value("${minio.secret-access-key}") String minioSecretAccessKey) {
        MinioEndPoint = minioEndPoint;
        minioClient = MinioClient.builder().endpoint(MinioEndPoint).credentials(minioAccessKeyId, minioSecretAccessKey).build();
    }

    public String getObjectPrefixUrl(String bucketName) {
        return String.format("https://%s/%s/", MinioEndPoint, bucketName);
    }

    public boolean bucketExists(String bucketName) throws Exception {
        return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
    }

    public boolean makeBucket(String bucketName) throws Exception {
        if (!bucketExists(bucketName)) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).region(Location).build());
        }
        return true;
    }

    public String getPresignedObjectUrl(String bucketName, String objectName, Integer expire) throws Exception {
        if (null == expire) {
            expire = DEFAULT_EXPIRY;
        }
        return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs
                .builder()
                .method(Method.GET)
                .bucket(bucketName)
                .object(objectName)
                .expiry(expire)
                .build());
    }

    public String putObject(String bucketName, String objectName, InputStream inputStream, String contentType) throws Exception {
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .contentType(contentType)
                .stream(inputStream, inputStream.available(), -1)
                .build());
        return getObjectPrefixUrl(bucketName) + objectName;
    }


}
